package com.example.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.example.system.dto.LoginDTO;
import com.example.system.dto.RegDTO;
import com.example.system.entity.User;
import com.example.system.mapper.UserMapper;
import com.example.system.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author yanyi
 * @since 2022-01-22
 */
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    //用户登录接口
    @Override
    public Map<String, Object> login(LoginDTO loginDTO) {
        HashMap<String, Object> map = new HashMap<>();
        String username = loginDTO.getUsername();
        String password = loginDTO.getPassword();
        String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username",username);
        userQueryWrapper.eq("password",md5Password);
        User user = userMapper.selectOne(userQueryWrapper);
        if (user != null){
            UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("username",username).set("login_time", LocalDateTime.now());
            userMapper.update(user,updateWrapper);
            map.put("code",200);
            map.put("msg","登录成功");
            map.put("data",user);
        }else {
            map.put("code",201);
            map.put("msg","登录失败");
        }
        return map;
    }

    //用户注册接口
    @Override
    public Map<String, Object> reg(RegDTO regDTO) {
        HashMap<String, Object> map = new HashMap<>();
        User user = new User();
        user.setUsername(regDTO.getUsername());
        String md5Password = DigestUtils.md5DigestAsHex(regDTO.getPassword().getBytes());//MD5加密
        user.setPassword(md5Password);
        user.setNickName(regDTO.getNickName());
        user.setRole(regDTO.getRole());
        boolean isSave = save(user);
        if (isSave){
            map.put("code",200);
            map.put("msg","注册成功");
            map.put("data",user);
        }else {
            map.put("code",201);
            map.put("msg","注册失败");
        }
        return map;
    }

    @Override
    public Map<String, User> listByName() {
        HashMap<String, User> map = new HashMap<>();
        List<User> users = list();
        users.forEach(user -> {map.put(user.getUsername(),user);});
        return map;
    }
}
